package JDBC;

import java.io.*;
import java.net.URL;
import java.sql.*;
import java.util.Properties;


/**
 * JDBC工具类
 */
public class JDBCUtil {
    private static String DB_URL;
    private static String USER;
    private static String PSW;
    private static String DRIVER;

    /**
     * 读取配置文件只需读取一次，用静态代码块
     */
    static {
        try {
            //1.创建Properties对象
            Properties properties = new Properties();
            //2.加载文件
            ClassLoader loader = JDBCUtil.class.getClassLoader();
            URL resource = loader.getResource("jdbc.properties");
            String path = resource.getPath();
            properties.load(new FileReader(path));
            //3.获取数据
            DB_URL = properties.getProperty("URL");
            USER = properties.getProperty("USER");
            PSW = properties.getProperty("PSW");
            DRIVER= properties.getProperty("DRIVER");
            //4.注册驱动
            Class.forName(DRIVER);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取链接
     *
     * @return Connection对象
     */
    public static Connection openConn() throws SQLException {

       return DriverManager.getConnection(DB_URL,USER,PSW);
    }


    /**
     * 释放资源
     * @param statement
     * @param connection
     */
    public static void close( Statement statement, Connection connection) {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 释放资源
     *
     * @param resultSet
     * @param statement
     * @param connection
     */
    public static void close(ResultSet resultSet, Statement statement, Connection connection) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
